package controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.johnyu.util.WebServiceUtil;
import po.Dish;
import po.Merchant;
import service.DishService;
import service.MerchantService;
import util.Po2Vo;
import vo.DishVo;
import vo.MerchantVo;

@Controller
public class MerchantController {

	@Autowired
	private MerchantService merchantService;
	@Autowired
	private DishService dishService;

	@RequestMapping("/index")
	public ModelAndView findAllMerchants() {
		ModelAndView mv = new ModelAndView();
		List<String> didList = new ArrayList<String>();
		List<String> midList = new ArrayList<String>();
		try{
			didList = WebServiceUtil.adDish();
			midList = WebServiceUtil.backMerchant();
		} catch (Exception e1) {
			System.out.println("connection is not found");
		}
		
		for(String id:didList){
				System.out.println("The AD dish id is : " + id + "===================");
		}
		
		for(String id : midList){
			System.out.println("The black merchant id is :" + id + "==================");
		}
		
		List<Dish> dishList = dishService.getAdDish(didList);
	
		List<Merchant> mList = merchantService.findAllMerchant(midList);

		mv.addObject("dLish", dishList);
		mv.setViewName("mlist");
		mv.addObject("mList", mList);
		return mv;
	}

	@RequestMapping("/merchant/{mid}")
	public ModelAndView findDishByMid(@PathVariable String mid, HttpSession session) {
		ModelAndView mv = new ModelAndView();
		MerchantVo merchantVo = merchantService.findMerchantByMid(mid);

		Map<String, Map<String, Integer>> carts = (Map<String, Map<String, Integer>>) session.getAttribute("carts");
		List<DishVo> cartList = new ArrayList<DishVo>();
		if (carts != null && carts.containsKey(mid) && carts.get(mid) != null) {
			Map<String, Integer> dishCarts = carts.get(mid);
			for (Dish d : merchantVo.getDishs()) {
				if (dishCarts.containsKey(d.getdId())) {
					cartList.add(Po2Vo.dishPo2Vo(d, dishCarts.get(d.getdId())));
				}
			}
		}
		mv.addObject("cartList", cartList);
		mv.addObject("merchant", merchantVo);
		mv.setViewName("dList");
		return mv;
	}

}
